package org.embedchat.protocol.codec.server;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;

import org.embedchat.protocol.Constants;
import org.embedchat.protocol.codec.AbstractMessageEncoder;
import org.embedchat.protocol.message.AbstractMessage;
import org.embedchat.protocol.message.server.RoomsListMessage;

@SuppressWarnings("unchecked")
public class RoomsListMessageEncoder extends AbstractMessageEncoder {

    private static final Set TYPES;

    static {
        Set types = new HashSet();
        types.add(RoomsListMessage.class);
        TYPES = Collections.unmodifiableSet(types);
    }
	
	public RoomsListMessageEncoder() {
		super(Constants.ROOMS_LIST_MESSAGE);
	}

	@Override
    protected void encodeBody(IoSession session, AbstractMessage message,
                              ByteBuffer outBuffer) {
		RoomsListMessage m = (RoomsListMessage) message;
        DataOutputStream out = new DataOutputStream(outBuffer.asOutputStream());
        try {
        	int roomsCount = m.getRoomsCount();
        	out.writeInt(roomsCount);
        	for (int i = 0; i < roomsCount; i++) {
        		out.writeInt(m.getRooms().get(i).getRoomId());
                out.writeUTF(m.getRooms().get(i).getRoomName());        		
        	}
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Set getMessageTypes() {
        return TYPES;
    }
}
